<!-- Author: Logan.Li -->
<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>个人中心</h1>
    </div>
    
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
        </div>
      </template>
      
      <div class="profile-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="avatar-section">
              <el-avatar :size="120" :icon="UserFilled" />
              <h3>{{ userInfo.name }}</h3>
              <p>{{ userInfo.username }}</p>
            </div>
          </el-col>
          
          <el-col :span="16">
            <div class="info-section">
              <el-descriptions title="基本信息" :column="2" border>
                <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="角色">{{ userInfo.role }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ userInfo.email || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="登录时间">{{ loginTime }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag type="success">正常</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="password-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        style="max-width: 500px;"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码（至少6位）"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="changing">
            修改密码
          </el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
// Author: Logan.Li
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'

const passwordFormRef = ref()
const changing = ref(false)
const userStore = useUserStore()

// 用户信息
const userInfo = ref({
  username: '',
  name: '',
  role: '',
  email: ''
})

// 登录时间
const loginTime = ref(new Date().toLocaleString())

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changing.value = true
      try {
        const response = await request.post('/user/changePassword/', {
          username: userInfo.value.username,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        
        console.log('修改密码API响应:', response);
        if (response.code === 20000) {
          ElMessage.success('密码修改成功，请重新登录')
          resetPasswordForm()
          // 3秒后跳转到登录页
          setTimeout(() => {
            localStorage.clear()
            window.location.href = '/login'
          }, 3000)
        } else {
          ElMessage.error(response.msg || '密码修改失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('修改密码失败:', error)
      } finally {
        changing.value = false
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 加载用户信息
const loadUserInfo = () => {
  // 从用户store获取当前用户信息
  userStore.initUserInfo()
  const currentUsername = userStore.getCurrentUsername()
  
  userInfo.value = {
    username: currentUsername,
    name: currentUsername === 'super123' ? 'Super管理员' : '管理员',
    role: userStore.userInfo.role || '管理员',
    email: userStore.userInfo.email || ''
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
/* 统一页面容器样式 - Author: Logan.Li */
.page-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f5f5;
}

/* 统一页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-content {
  padding: 20px 0;
}

.avatar-section {
  text-align: center;
  padding: 20px;
}

.avatar-section h3 {
  margin: 15px 0 5px 0;
  color: #303133;
}

.avatar-section p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.info-section {
  padding: 20px 0;
}

.password-card {
  margin-top: 20px;
}

/* 统一卡片样式 */
.profile-card, .password-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
